<template>
  <ToolbarButton
    icon="i-ri-format-clear"
    title="清除格式"
    :disabled="isDisabled"
    @click="handleClick"
  />
</template>

<script setup lang="ts">
import { computed, inject, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import ToolbarButton from "../../../button/index.vue";

defineOptions({
  name: "ClearFormat",
});

// 注入编辑器实例
const editor = inject<Ref<Editor>>("editor");

// 检查是否有格式可以清除
const isDisabled = computed(() => {
  if (!editor?.value) return true;

  const { state } = editor.value;
  const { selection } = state;

  // 如果没有选中文本，检查当前段落是否有格式
  if (selection.empty) {
    return (
      !editor.value.isActive("bold") &&
      !editor.value.isActive("italic") &&
      !editor.value.isActive("underline") &&
      !editor.value.isActive("strike") &&
      !editor.value.isActive("highlight") &&
      !editor.value.isActive("code") &&
      !editor.value.isActive("textStyle") &&
      !editor.value.isActive("color") &&
      !editor.value.isActive("textAlign")
    );
  }

  return false;
});

const handleClick = () => {
  if (!editor?.value) return;

  editor.value?.chain().focus().unsetAllMarks().run();
};
</script>
